package com.find.answer.controller;

import cn.hutool.core.io.IoUtil;
import com.find.answer.domain.http.Result;
import lombok.Cleanup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @author Seon
 * @date 2022/10/25 22:15
 */
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {
    @Value("${ruiji.path}")
    private String basePath;

    @GetMapping("/download")
    public void downloadFile(@RequestParam("name") String fileName,
                             HttpServletResponse response) {
        String originalPath = basePath + fileName;
        try {
            @Cleanup FileInputStream is = new FileInputStream(originalPath);
            @Cleanup ServletOutputStream sos = response.getOutputStream();
            IoUtil.copy(is, sos);
            log.info("已下载文件" + originalPath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @PostMapping("/upload")
    public Result<?> uploadFile(MultipartFile file) {
        String originalName = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString();
        String suffix = originalName.substring(originalName.indexOf("."));
        String finalName = uuid + suffix;
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(dir + "\\" + finalName));
            log.info("已上传文件" + dir + finalName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(finalName);
    }
}
